using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AXBC = Microsoft.Dynamics.BusinessConnectorNet;
using AXMD = Microsoft.Dynamics.Framework.Metadata.Ax;
using Proxy = Microsoft.Dynamics.Framework.BusinessConnector.Proxy;

namespace DynamicsAXPS
{
    [System.Management.Automation.Cmdlet("Export", "AXTableReport")]
    public class Export_AXTableReport : System.Management.Automation.PSCmdlet
    {
        [System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
        public string Table;

        [System.Management.Automation.Parameter(Position = 1, Mandatory = true)]
        public string[] Fields = new string[] { "*" };

        [System.Management.Automation.Parameter(Position = 2, Mandatory = true)]
        public string Filename;


        protected override void ProcessRecord()
        {
            var ax_session = Microsoft.Dynamics.Framework.Portal.SessionHelper.Instance.GetSession();
            int table_id = AXMD.TableMetadata.TableNum(ax_session, this.Table);

            var md = AXMD.MetadataCache.GetTableMetadata(ax_session, table_id);

            var field_names = this.Fields;
            var fields = DynamicsAXUtil.AXDataUtil.GetReal_fields(this.Table, this.Fields);

            foreach (var field in fields)
            {
                this.WriteVerbose(string.Format("Field: {0}", field));
            }

            var map = md.Fields.ToDictionary(f => f.Name);



            var map_id_to_edt = new Dictionary<int, Microsoft.Dynamics.Framework.Metadata.Ax.ExtendedDataTypeMetadata>();

            var field_objects = fields.Select(f => map[f]).ToList();

            foreach (var field_object in field_objects)
            {
                this.WriteVerbose(string.Format("FieldObjectName: {0}", field_object.Name));

                int edt_id = field_object.ExtendedDataTypeId;
                if (edt_id > 0 && (!map_id_to_edt.ContainsKey(edt_id)))
                {
                    map_id_to_edt[edt_id] = AXMD.MetadataCache.GetExtendedDataTypeMetadata(ax_session, edt_id);
                }
            }

            var fp = System.IO.File.CreateText(Filename);
            fp.AutoFlush = true;

            var x = new System.Xml.XmlTextWriter(fp);
            x.Formatting = System.Xml.Formatting.Indented;

            x.WriteStartDocument();
            x.WriteStartElement("html");

            x.WriteStartElement("head");

            x.WriteStartElement("style");
            x.WriteString(@"

		body,tbody
		{
		    font-family: Segoe UI;
		    font-size: 8pt;
		}

		table
		{
		    border-spacing: 0;
		    border-collapse: collapse;
		}

		th
		{
		    text-align:left; 
		    vertical-align:bottom;
		}

		td {
		    border-style: solid;
		    border-width: 1px;
		    border-color: #d0d0d0;
		    vertical-align: top;
		}
		");
            x.WriteEndElement();//style

            x.WriteEndElement();//head

            x.WriteStartElement("body");

            x.WriteElementString("p", string.Format("Table: {0}", this.Table));
            x.WriteStartElement("table");

            x.WriteStartElement("tr");
            foreach (var field_object in field_objects)
            {
                x.WriteElementString("th", field_object.Name);
            }
            x.WriteEndElement();//tr

            x.WriteStartElement("tr");
            foreach (var field_object in field_objects)
            {
                x.WriteElementString("th", "Align: " + field_object.Alignment.ToString());
            }
            x.WriteEndElement();//tr


            x.WriteStartElement("tr");
            foreach (var field_object in field_objects)
            {
                int edt_id = field_object.ExtendedDataTypeId;
                if (edt_id > 0)
                {
                    var edt_md = AXMD.MetadataCache.GetExtendedDataTypeMetadata(ax_session, edt_id);
                    x.WriteElementString("th", "EDT: " + edt_md.Name);
                }
            }
            x.WriteEndElement();//tr

            var dt = DynamicsAXUtil.AXDataUtil.GetAXTableData(this.Table, fields);

            foreach (System.Data.DataRow row in dt.Rows)
            {
                x.WriteStartElement("tr");

                foreach (var i in row.ItemArray)
                {
                    var cellval = "";
                    if (i != null)
                    {
                        cellval = i.ToString();
                    }
                    x.WriteElementString("td", cellval);
                }

                x.WriteEndElement();//tr
            }


            x.WriteEndElement();//table

            x.WriteEndElement();//body

            x.WriteEndElement(); //html


            x.WriteEndDocument(); //document

            x.Flush();
            x.Close();

        }
    }
}
